import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

import { BaseService, RestResult, PagedQueryResult, RefBean } from 'iisp-ng';

import { TableInfo, TableTemplate, DataImport, DataImportAction, DataImportQueryParam, DataExportRequest, NodeImportState } from './model';

declare var restRoot: string;

@Injectable()
export class DataIEService extends BaseService {
	private dataieUrl = restRoot + '/iisp-data-ie';

	constructor(http: HttpClient) { super(http); }

	getTableList(): Observable<TableInfo[]> {
		let url = `${this.dataieUrl}/tables`;
		return this.doGet(url);
	}

	getTableTemplateList(tableName: string): Observable<TableTemplate[]> {
		let url = `${this.dataieUrl}/templates?tableName=${tableName}`;
		return this.doGet(url);
	}

	getDataExportRequest(tableName: string): Observable<DataExportRequest> {
		let url = `${this.dataieUrl}/exportRequests/tables/${tableName}`;
		return this.doGet(url);
	}
	exportData(dataExport: DataExportRequest): Observable<RestResult> {
		let url = `${this.dataieUrl}/exports`;
		return this.doPost(url, dataExport);
	}

	delTemplate(id: number): Observable<void> {
		let url = `${this.dataieUrl}/templates/${id}`;
		return this.doDelete(url);
	}

	newTableTemplate(tplt: TableTemplate): Observable<TableTemplate> {
		let url = `${this.dataieUrl}/templates`;
		return this.doPost(url, tplt);

	}

	updateTableTemplate(tplt: TableTemplate): Observable<void> {
		let url = `${this.dataieUrl}/templates/${tplt.id}`;
		return this.doPut(url, tplt);
	}

	genDefaultTableTemplate(table: TableInfo): Observable<TableTemplate> {
		let tplt = {
			tabName: table.code,
			dscName: table.name
		}
		let url = `${this.dataieUrl}/templates?genDefault=y`;
		return this.doPost(url, tplt);

	}

	getDataImports(queryParam: DataImportQueryParam): Observable<PagedQueryResult<DataImport>> {
		let url = `${this.dataieUrl}/imports`;
		return this.searchPage(url, queryParam);
	}

	importData(dImport: DataImport): Observable<DataImport> {
		let url = `${this.dataieUrl}/imports`;
		return this.doPost(url, dImport);
	}
	dataImportAction(id: number, dataImportAction: DataImportAction): Observable<DataImport> {
		let url = `${this.dataieUrl}/imports/${id}`;
		return this.doPost(url, dataImportAction);
	}
	getNodeImportStateTableList(): Observable<RefBean[]> {
		let url = `${this.dataieUrl}/node-import-tables`;
		return this.doGet(url);
	}
	///node-import-states/tables/{tableCode}
	getNodeImportStates(tableCode: string, dataDate: string): Observable<NodeImportState[]> {
		let url = `${this.dataieUrl}/node-import-states/tables/${tableCode}?dataDate=${dataDate}`;
		return this.doGet(url);
	}
	getNodeList(): Observable<any> {
		let url = restRoot + "/iisp-base/dict/langMap/NODE_LIST";
		return this.doGet(url);
	}
}